package com.work.csms.controller;

import com.work.csms.dao.Fix;
import com.work.csms.dao.Station;
import com.work.csms.pojo.PageParam;
import com.work.csms.service.FixService;
import com.work.csms.service.StationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/fix")
@CrossOrigin(originPatterns = "*",allowCredentials ="true")
public class FixController {

    @Autowired(required = false)
    private FixService fixService;
    @Autowired(required = false)
    private StationService stationService;

    @PostMapping("/page")
    public Map<String, Object> page(@RequestBody Fix fix, @RequestBody PageParam pageParam) throws Exception {
        return fixService.page(fix, pageParam);
    }

    @RequestMapping("/list")
    public List<Fix> list(@RequestBody Fix fix) throws Exception {
        return fixService.list(fix);
    }

    @PostMapping("/getFixCountByDate")
    public Integer getFixCountByDate(@RequestBody Fix fix) throws Exception {
        return fixService.getFixCountByDate(fix);
    }

    @RequestMapping("/getFixById")
    public Fix getFixById(@RequestBody Fix fix) throws Exception {
        Integer id = fix.getId();
        if(id == null) {
            return null;
        } else {
            return fixService.getFixById(id);
        }
    }

    @RequestMapping("/saveOrUpdate")
    public Map<String, Object> saveOrUpdate(@RequestBody Fix fix) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Integer id = fix.getId();
        if (Objects.isNull(id)) {
            fix.setStart(new Date());
            fixService.save(fix);
        } else {
            if (fix.getStatu().equals("维修中")) {
                Station station = new Station();
                station.setId(fix.getStationid());
                station.setStatu(fix.getStatu());
                stationService.update(station);
            } else if (fix.getStatu().equals("完成")) {
                Station station = new Station();
                station.setId(fix.getStationid());
                station.setStatu("正常");
                stationService.update(station);
            }
            fix.setEnd(new Date());
            fixService.update(fix);
        }
        result.put("success", true);
        return result;
    }

    @RequestMapping("/deleted")
    public Map<String, Object> deleted(@RequestBody Fix fix) throws Exception {
        Map<String, Object> result = new HashMap<>();
        Integer id = fix.getId();
        if (Objects.isNull(id)) {
            result.put("msg", "报修id不存在");
        } else {
            fixService.deleted(fix.getId());
            result.put("success", true);
        }
        return result;
    }
}
